# -*- coding: utf-8 -*-

# Copyright (c) 2025 Lijiang
# Licensed under the MIT License
# See LICENSE file for details

"""
视频压缩核心模块 - 仅使用FFmpeg
"""

import os
import logging
from typing import List, Optional, Callable, Union
from PyQt6.QtCore import QObject, pyqtSignal

from .file_handler import FileHandler
from .ffmpeg_compressor import FFmpegVideoCompressor
from .thread_pool_manager import ThreadPoolManager

logger = logging.getLogger(__name__)


class VideoCompressor:
    """视频压缩器主类 - 仅使用FFmpeg"""
    
    def __init__(self, ffmpeg_path: str = None, max_workers: int = 2):
        """
        初始化视频压缩器
        
        Args:
            ffmpeg_path: FFmpeg可执行文件路径，None表示自动检测
            max_workers: 最大并发工作线程数
        """
        self.ffmpeg_compressor = FFmpegVideoCompressor(ffmpeg_path)
        self.thread_pool = ThreadPoolManager(max_workers)
        self.workers = []  # 存储直接创建的工作线程
        self.temp_files = []  # 存储临时文件
    
    def compress_video(self, input_path: str, output_path: str, compression_ratio: float,
                      progress_callback: Optional[Callable] = None,
                      status_callback: Optional[Callable] = None,
                      finished_callback: Optional[Callable] = None,
                      file_info_callback: Optional[Callable] = None,
                      use_thread_pool: bool = True) -> Union[str, object]:
        """
        压缩单个视频文件
        
        Args:
            input_path: 输入视频文件路径
            output_path: 输出视频文件路径
            compression_ratio: 压缩比例 (0.1-0.9)
            progress_callback: 进度回调函数
            status_callback: 状态回调函数
            finished_callback: 完成回调函数
            file_info_callback: 文件信息回调函数
            use_thread_pool: 是否使用线程池管理
            
        Returns:
            任务ID（线程池模式）或工作线程对象（直接模式）
        """
        ############################### 创建输出路径 ###############################
        if not output_path:
            output_path = FileHandler.generate_output_path(input_path, compression_ratio)
        
        if use_thread_pool:
            ############################### 使用线程池管理 ###############################
            task_id = self.thread_pool.add_task(
                input_path, output_path, compression_ratio,
                progress_callback, status_callback, finished_callback, file_info_callback
            )
            return task_id
        else:
            ############################### 直接使用FFmpeg压缩器 ###############################
            worker = self.ffmpeg_compressor.compress_video(
                input_path, output_path, compression_ratio,
                progress_callback, status_callback, finished_callback, file_info_callback
            )
            self.workers.append(worker)
            return worker
    
    def cancel_all(self):
        """取消所有压缩任务"""
        if self.ffmpeg_compressor:
            self.ffmpeg_compressor.cancel_all()
        if self.thread_pool:
            self.thread_pool.cancel_all_tasks()
        
        ############################### 清理临时文件 ###############################
        FileHandler.cleanup_temp_files(self.temp_files)
        self.temp_files.clear()
    
    def cancel_worker(self, worker_or_task_id):
        """
        取消指定的压缩任务
        
        Args:
            worker_or_task_id: 工作线程对象或任务ID
            
        Returns:
            bool: 是否成功取消
        """
        if isinstance(worker_or_task_id, str):
            ############################### 取消线程池中的任务 ###############################
            return self.thread_pool.cancel_task(worker_or_task_id)
        elif hasattr(worker_or_task_id, 'cancel'):
            ############################### 取消FFmpeg工作线程 ###############################
            return self.ffmpeg_compressor.cancel_worker(worker_or_task_id)
        return False
    
    def get_active_workers(self):
        """获取活跃的工作线程"""
        active_tasks = []
        if self.thread_pool:
            active_tasks.extend(self.thread_pool.get_active_tasks())
        if self.ffmpeg_compressor:
            active_tasks.extend(self.ffmpeg_compressor.get_active_workers())
        return active_tasks
    
    def cleanup_finished_workers(self):
        """清理已完成的工作线程"""
        if self.ffmpeg_compressor:
            self.ffmpeg_compressor.cleanup_finished_workers()
        if self.thread_pool:
            self.thread_pool.clear_completed_tasks()
    
    def get_queue_status(self):
        """获取队列状态"""
        if self.thread_pool:
            return self.thread_pool.get_queue_status()
        else:
            return {
                'active_count': len(self.get_active_workers()),
                'pending_count': 0,
                'completed_count': 0,
                'max_workers': 1
            }
    
    def set_max_workers(self, max_workers: int):
        """设置最大工作线程数"""
        if self.thread_pool:
            self.thread_pool.set_max_workers(max_workers)
    
    def is_ffmpeg_available(self) -> bool:
        """检查FFmpeg是否可用"""
        return self.ffmpeg_compressor.is_ffmpeg_available()
    
    def get_ffmpeg_version(self) -> str:
        """获取FFmpeg版本信息"""
        return self.ffmpeg_compressor.get_ffmpeg_version()